package com.xintoucloud.pbs.dao.impl;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xintoucloud.pbs.dao.NewsManagementDao;
import com.xintoucloud.pbs.entity.DynamicNews;
import com.xintoucloud.pbs.entity.DynamicNewsTopic;
import com.xintoucloud.pbs.model.DynamicNewsShowVo;


@Repository
public class NewsManagementDaoImpl implements NewsManagementDao {
	@Autowired
	private SessionFactory sessionFactory;


	@Override
	public DynamicNews getOne(int nid) {
		DynamicNews d = sessionFactory.getCurrentSession().get(DynamicNews.class, nid);
		return d;
	}

	@Override
	public DynamicNewsShowVo getOneShowVo(int nid) {
		Object[] o  = (Object[]) sessionFactory.getCurrentSession().createQuery("select d.nid,d.title,d.source,d.createtime,d.newspic,d.content,d.dnt.tname,d.dnt.ntid from DynamicNews d where nid=?0").setParameter(0, nid).uniqueResult();
		DynamicNewsShowVo vo = new DynamicNewsShowVo();
		vo.setNid((int)o[0]);
		vo.setTitle((String)o[1]);
		vo.setSource((String)o[2]);
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		vo.setCreatetime(sdf.format((Date)o[3]));
		vo.setNewspic((String)o[4]);
		vo.setContent((String)o[5]);
		vo.setTopic((String)o[6]);
		vo.setNtid((int)o[7]);
		return vo;
	}

	@Override
	public List<DynamicNewsShowVo> list() {
		List<Object[]> list  = sessionFactory.getCurrentSession().createQuery("select d.nid,d.title,d.source,d.createtime,d.newspic,d.content,d.dnt.tname,d.dnt.ntid from DynamicNews d").list();
		//list = sessionFactory.getCurrentSession().createQuery("from DynamicNews").list();
		List<DynamicNewsShowVo> vos = new ArrayList<>(); 
		for(Object[] o: list) {
			DynamicNewsShowVo vo = new DynamicNewsShowVo();
			vo.setNid((int)o[0]);
			vo.setTitle((String)o[1]);
			vo.setSource((String)o[2]);
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
			vo.setCreatetime(sdf.format((Date)o[3]));
			vo.setNewspic((String)o[4]);
			vo.setContent((String)o[5]);
			vo.setTopic((String)o[6]);
			vo.setNtid((int)o[7]);
			vos.add(vo);
		}
		//System.out.println(list.size());
		return vos;
	}
	

	@Override
	public Serializable add(DynamicNews d) {
		return sessionFactory.getCurrentSession().save(d);
	}

	@Override
	public boolean delete(int nid) {
		DynamicNews d = getOne(nid);
		sessionFactory.getCurrentSession().delete(d);
		return true;
	}

	@Override
	public void update(DynamicNews d) {
		DynamicNews dd = getOne(d.getNid());
		dd.setTitle(d.getTitle());
		dd.setSource(d.getSource());
		dd.setCreatetime(d.getCreatetime());
		dd.setContent(d.getContent());
		dd.setDnt(d.getDnt());
		sessionFactory.getCurrentSession().update(dd);
	}

}
